package com.example.web.controller;

import com.example.common.response.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springsecurity-study
 * @description: 关于SpringSecurity的一些请求处理
 * @author: ChenZhiXiang
 * @create: 2019-07-28 16:07
 **/
@RestController
@Slf4j
public class SpringSecurityController {

    /** SpringSecurity自带的存储请求的缓存 */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /** SpringSecurity自带的跳转工具类 */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /** 默认的登录地址 */
    @Value("${login.page}")
    private String loginPage;

    /**
     * 当需要身份验证时跳到到这里
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/authentication/require")
    public Object requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 拿到请求
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if (null != savedRequest){
            String targetUrl =  savedRequest.getRedirectUrl();
            log.info("引发跳转的地址："+targetUrl);
            if (StringUtils.endsWithIgnoreCase(targetUrl,".html")){
                redirectStrategy.sendRedirect(request,response,loginPage);
            }
        }
        return ResponseData.FiledResponse("用户请求的需要验证，请先登录！");
    }

    @GetMapping("/session/invalid")
    public Object sessionInvalid() throws Exception {
        Map<String,Object> map = new HashMap<>();
        map.put("code",400);
        map.put("msg","session失效了");
        return ResponseData.turnResponse(map);
    }

}
